package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.item.pojo.Stock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-12-20 11:51
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult<SpuBo> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {


        PageHelper.startPage(page,rows);

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }

        if (null!=saleable){
            criteria.andEqualTo("saleable",saleable);
        }
        Page<Spu> spuPage = (Page<Spu>) this.spuMapper.selectByExample(example);

        List<SpuBo> spuBoList = new ArrayList<>();

        //把直接查询到的spu转为spuBo
        spuPage.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            BeanUtils.copyProperties(spu,spuBo);
            spuBo.setBname(this.brandService.getBrandById(spu.getBrandId()).getName());

            List<String> names = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));
            spuBo.setCname(StringUtils.join(names,"/"));

            spuBoList.add(spuBo);
        });

        return new PageResult<>(spuPage.getTotal(),new Long(spuPage.getPages()),spuBoList);
    }

    @Transactional
    public void saveGoods(SpuBo spuBo) {

        //添加没有包含的属性
        spuBo.setSaleable(true);
        spuBo.setValid(true);

        spuBo.setCreateTime(new Date());

        spuBo.setLastUpdateTime(spuBo.getCreateTime());

        //保存spu，回显ID
        this.spuMapper.insertSelective(spuBo);

        //给spuDetail添加spu的id
        spuBo.getSpuDetail().setSpuId(spuBo.getId());

        //保存spuDetail
        this.spuDetailMapper.insertSelective(spuBo.getSpuDetail());

        List<Sku> skus = spuBo.getSkus();

        //循环给sku赋值spu的id，并保存sku，回显Sku的id
        skus.forEach(sku->{
            sku.setSpuId(spuBo.getId());

            sku.setCreateTime(spuBo.getCreateTime());

            sku.setLastUpdateTime(spuBo.getCreateTime());

            this.skuMapper.insertSelective(sku);

            //保存sku的同时要保存stock
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());

            stock.setStock(sku.getStock());

            this.stockMapper.insertSelective(stock);
        });


        amqpTemplate.convertAndSend("item.insert",spuBo.getId());

    }

    public SpuDetail querySpuDetailById(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }


    //查询sku并同步查询 stock库存
    public List<Sku> querySkuBySpuId(Long spuId) {

        Sku record = new Sku();
        record.setSpuId(spuId);

        List<Sku> skus = this.skuMapper.select(record);

        skus.forEach(sku->{
            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        });
        return skus;
    }

    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //对于spu来说，只有时间需要手动
        spuBo.setLastUpdateTime(new Date());

       this.spuMapper.updateByPrimaryKeySelective(spuBo);

       this.spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());

       //操刀SKU

        //先获取原来数据库中当前spu下的sku
        Sku record = new Sku();
        record.setSpuId(spuBo.getId());
        List<Sku> dbSkus = this.skuMapper.select(record);


        //获取最新提交的sku
        List<Sku> newSkus = spuBo.getSkus();

        newSkus.forEach(newSku->{
            //新增的sku,直接保存,并同时保存库存
            if(null==newSku.getId()){
                newSku.setSpuId(spuBo.getId());
                newSku.setCreateTime(new Date());
                newSku.setLastUpdateTime(newSku.getCreateTime());

                this.skuMapper.insertSelective(newSku);

                Stock stock = new Stock();
                stock.setSkuId(newSku.getId());
                stock.setStock(newSku.getStock());

                this.stockMapper.insertSelective(stock);

            }else{//要被修改的sku，同步修改库存
                newSku.setSpuId(spuBo.getId());
                newSku.setLastUpdateTime(new Date());

                this.skuMapper.updateByPrimaryKeySelective(newSku);


                Stock stock = new Stock();
                stock.setSkuId(newSku.getId());
                stock.setStock(newSku.getStock());

                this.stockMapper.updateByPrimaryKeySelective(stock);

                //TODO 在这里要把这玩意从数据库中所有的 查询结果中 删除
                dbSkus.removeIf(sku -> sku.getId().longValue()==newSku.getId().longValue());
            }
        });

        dbSkus.forEach(dbSku->{
            //下架处理
            dbSku.setEnable(false);

            this.skuMapper.updateByPrimaryKeySelective(dbSku);
        });
        amqpTemplate.convertAndSend("item.update",spuBo.getId());
    }

    public Spu querySpuById(Long spuId) {
        return this.spuMapper.selectByPrimaryKey(spuId);
    }
}
